#include "abc-server.h"

#include "util/logger/logger.h"
#include "util/net/io-context.h"
#include "util/net/http-server-on-tcp.h"
#include "util/net/http-server-on-ssl.h"
#include "util/html/template/factory.h"
#include "util/config/preference-entry.h"
#include "util/config/ui-path.h"

#include "abc-server-dispatcher.h"

static const PreferenceEntry<uint16_t> prefHttpPort("http.port", 8000);

static const PreferenceEntry<uint16_t> prefHttpsPort("https.port", 9000);
static const PreferenceEntry<UiPath> prefHttpsCert("https.cert");
static const PreferenceEntry<UiPath> prefHttpsKey("https.key");

static const PreferenceEntry<UiPath> prefHtmlTemplateRootDir("html.template.rootdir");

AbcServer::AbcServer()
    : title_("AbcServer ")
    , ioContext_(new IOContext)
    , dispatcher_(new AbcServerDispatcher(*this))
    , httpServerOnTCP_(new HttpServerOnTCP(*ioContext_, *prefHttpPort, *dispatcher_))
    , httpServerOnSSL_(new HttpServerOnSSL(*ioContext_, *prefHttpsPort, *dispatcher_, *prefHttpsCert, *prefHttpsKey))
    , htmlTemplateFactory_(new html::tmplt::Factory(*prefHtmlTemplateRootDir)) {

    LOGD << title() << "constructed";
}

AbcServer::~AbcServer() {
    LOGD << title() << "destructed";

    delete htmlTemplateFactory_;
    htmlTemplateFactory_ = nullptr;

    delete httpServerOnTCP_;
    httpServerOnTCP_ = nullptr;

    delete dispatcher_;
    dispatcher_ = nullptr;

    delete ioContext_;
    ioContext_ = nullptr;
}

void AbcServer::exec() {
    ioContext_->exec();
}

Executor &AbcServer::executor() {
    return *ioContext_;
}


